import { createStore } from 'vuex'
import { $http } from '@/utils/Axios.js'
import pic from '@/assets/logo.png'
export default createStore({
  state: {
    // 播放列表
    playList: [
      {
        al: {
          picUrl: pic
        },
        name: '发现好音乐',
        id: 1111
      }
    ],
    // 当前播放得音乐下标
    playListIndex: 0,
    // 播放按钮状态
    musicState: true,
    // 歌曲详情页面状态
    showMusicPage: false,
    // 当前播放得音乐歌词
    currentMusicLyric: '发现好音乐',
    // 当前播放得音乐歌词对应时间
    currentMusicLyricPosition: 0,
    // 当前播放的音乐总时长
    currentMusicTime: 0,
    // 主页切换头部的名称
    activeName: 'home',
    // 底部音乐栏是否显示
    footerMusicShowState: true,
    // 音乐链接
    musicUrl: '',
    // 弹出音乐列表状态
    popupMusicList: false
  },
  getters: {},
  mutations: {
    setPlayList(state, value) {
      state.playList = value
    },
    musicStateChange(state, value) {
      state.musicState = value
    },
    playListIndexChange(state, value) {
      if (value === undefined) {
        return (state.playListIndex = state.playList.length - 1)
      }
      state.playListIndex = value
    },
    showMusicPageState(state, value) {
      state.showMusicPage = value
    },
    setCurrentMusicLyric(state, value) {
      state.currentMusicLyric = value
    },
    setcurrentMusicLyricPosition(state, value) {
      state.currentMusicLyricPosition = value
    },
    switchMusic(state, value) {
      state.playListIndex += value
    },
    setCurrentMusicTime(state, value) {
      state.currentMusicTime = value
    },
    pushNewMusicToList(state, value) {
      state.playList.push(value)
    },
    changeActiveName(state, value) {
      state.activeName = value
    },
    footerMusicShowStateChange(state, value) {
      state.footerMusicShowState = value
    },
    popupMusicListState(state, value) {
      state.popupMusicList = value
    }
  },
  actions: {
    async getMusicUrl(context, value) {
      const { data: res } = await $http.get('song/url?id=' + value)
      context.state.musicUrl = res.data[0].url
    },
    // 发起ajax请求获取对应id的歌曲的歌词
    async getLyric(context, value) {
      const { data: res } = await $http.get('lyric?id=' + value)
      if (res.lrc.lyric) {
        context.commit('setCurrentMusicLyric', res.lrc.lyric)
      }
    },
    // 切换歌词前判断下标的，如果小于0切换到最后一首，如果等于歌单长度切换到第一首，否则直接切换
    beforeSwitchMusic(context, value) {
      if (context.state.playListIndex + value < 0) {
        context.commit('switchMusic', context.state.playList.length - 1)
      } else if (
        context.state.playListIndex + value ===
        context.state.playList.length
      ) {
        context.commit('switchMusic', -(context.state.playList.length - 1))
      } else {
        context.commit('switchMusic', value)
      }
    }
  },
  modules: {}
})
